package com.cacho.s2b.lesson.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.impl.DefaultJwtBuilder;
import io.jsonwebtoken.security.SecureDigestAlgorithm;

import java.security.PrivateKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTCustom {
    private static final String ISSUER = "CACHO";
    private static final String AUDIENCE = "CACHO-API";

    public static String generateJWT(long timeout, Map<String, String> payload, String privateKey, String... alg) {
        SecureDigestAlgorithm signAlg = Jwts.SIG.RS256;
        if (alg.length > 0 && alg[0].equalsIgnoreCase("PS256")) {
            signAlg = Jwts.SIG.PS256;
        }
        PrivateKey privateKey1 = new EncryptHelper().StringToPrivateKey(privateKey);
        DefaultJwtBuilder jwt = new DefaultJwtBuilder();
        // 对body 处理成 json格式
        Map<String, Object> payload0 = new HashMap<>();
        if (payload != null) {
            for (Map.Entry<String, String> entry : payload.entrySet()) {
                try {
                    Map obj = new ObjectMapper().readValue(entry.getValue(), Map.class);
                    payload0.put(entry.getKey(), new Gson().toJsonTree(obj));
                } catch (Exception e) {
                    payload0.put(entry.getKey(), new Gson().toJsonTree(entry.getValue()));
                }
            }
            jwt.setClaims(payload0);
        }
        jwt.setAudience(AUDIENCE);
        jwt.setIssuedAt(new Date(System.currentTimeMillis()));
        jwt.setNotBefore(new Date(System.currentTimeMillis()));
        jwt.setExpiration(new Date(System.currentTimeMillis() + timeout * 1000));
        jwt.signWith(privateKey1, signAlg);
        return jwt.compact();
    }
}
